﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
using System.Xml;

namespace Admin
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        string configPath = string.Empty;
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            using (RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"Software\henk", false))
            {
                if (key != null)
                {
                    string path = key.GetValue("iytong health path").ToString();
                    if (!string.IsNullOrEmpty(path))
                    {
                        configPath = string.Format("{0}\\Health Solution.exe.config", path);
                        if (!File.Exists(configPath))
                        {
                            MessageBox.Show("在安装目录没有找到配置文件！");
                            this.Close();
                        }

                        string text = File.ReadAllText(configPath);

                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.LoadXml(text);
                        var node = xmlDoc.SelectSingleNode("configuration/connectionStrings");
                        var config = node.FirstChild;
                        string allconnStr = config.Attributes["connectionString"].Value;
                        var ary = allconnStr.Trim('"').Substring(allconnStr.IndexOf("Server")).Split(';');
                        if (ary.Length >= 4)
                        {
                            foreach (var str in ary)
                            {
                                var hashItem = str.Split('=');
                                if (hashItem[0].ToLower() == "server")
                                    tbIP.Text = hashItem[1];

                                if (hashItem[0].ToLower() == "database")
                                    tbName.Text = hashItem[1];

                                if (hashItem[0].ToLower() == "uid")
                                    tbUser.Text = hashItem[1];

                                if (hashItem[0].ToLower() == "pwd")
                                    tbPsd.Password = hashItem[1];
                            }

                            if (string.IsNullOrEmpty(tbIP.Text) || string.IsNullOrEmpty(tbName.Text)
                                || string.IsNullOrEmpty(tbUser.Text) || string.IsNullOrEmpty(tbPsd.Password))
                            {
                                MessageBox.Show("配置文件格式错误！");
                                this.Close();
                            }
                        }
                        else
                        {
                            MessageBox.Show("配置文件读取错误！");
                            this.Close();
                        }

                    }
                }
                else
                {
                    MessageBox.Show("程序未安装！");
                    this.Close();
                }
            }
        }

        private static string template = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <connectionStrings>\r\n    <add name=\"HealthEntities\" connectionString=\"metadata=res://*/Data.Health.csdl|res://*/Data.Health.ssdl|res://*/Data.Health.msl;provider=System.Data.SqlClient;provider connection string=&quot;Server=@ServerName;Database=@DbName;Uid=@UserName;Pwd=@Password;MultipleActiveResultSets=True&quot;\" providerName=\"System.Data.EntityClient\" />\r\n  </connectionStrings>\r\n</configuration>";
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string ip = tbIP.Text;
            string dbName = tbName.Text;
            string userName = tbUser.Text;
            string psd = tbPsd.Password;

            string xml = template.Replace("@ServerName", ip).Replace("@DbName", dbName).Replace("@UserName", userName).Replace("@Password", psd);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            xmlDoc.Save(configPath);;

            MessageBox.Show("保存成功！");
            this.Close();
        }
    }
}
